#include <stdio.h>
#include <time.h>
#include "tme_utils.h"

#if defined(WIN32) || defined(WIN64) || defined(WINCE) || defined(_MSC_VER)
/* ---------- Windows begin ---------- */
#include <windows.h>
#include <io.h>

uint32_t tme_utils_getTickUs()
{
    return clock() * 1000;
}

uint32_t tme_utils_getTickMs()
{
    return clock();
}

void tme_utils_delayms(int32_t ms)
{
    Sleep(ms);
}
/* ---------- Windows end ---------- */
#else
/* ---------- Linux begin ---------- */
#include <unistd.h>
#include <sys/time.h>

uint32_t tme_utils_getTickUs()
{
    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    return (uint32_t)(tv.tv_sec * 1000000u + tv.tv_usec);
}

uint32_t tme_utils_getTickMs()
{
    struct timeval tv = {0};
    gettimeofday(&tv, NULL);
    return (uint32_t)(tv.tv_sec * 1000u + tv.tv_usec / 1000u);
}

void tme_utils_delayms(int32_t ms)
{
    usleep(ms * 1000);
}
/* ---------- Linux end ---------- */
#endif

void tme_utils_getTime(uint16_t* year, uint8_t* month, uint8_t* day, uint32_t* sec)
{
    time_t now;
    struct tm *time_now;
    time(&now);
    time_now = localtime(&now);
    *year = (uint16_t)time_now->tm_year + 1900;
    *month = (uint8_t)time_now->tm_mon + 1;
    *day = (uint8_t)time_now->tm_mday;
    *sec = ((time_now->tm_hour + 0) % 24) * 3600 + time_now->tm_min * 60 + time_now->tm_sec;
}

int32_t tme_utils_strcmp(const char* src, const char* dst, char endFlags)
{
    while (*src && *dst)
    {
        /* 中途出现不一致 */
        if (*src != *dst) {
            return (*src) > (*dst) ? 99 : (-99);
        }
        src += 1;
        dst += 1;
    }
    /* 其中一方为0,另一方为结束符 */
    if (endFlags != 0 && *src == endFlags && *dst == '\0') {
        return 1; /* 前者比后者长 */
    }
    else if (endFlags != 0 && *src == '\0' && *dst == endFlags) {
        return -1; /* 后者比前者长 */
    }
    /* 其中一方为0,另一方未结束 */
    else if (*src != *dst) {
        return (*src) > (*dst) ? 99 : (-99);
    }
    /* 双方同时结束字符串 */
    return 0;
}
